<template>
  <BasicDrawer
      :destroyOnClose="true"
      v-bind="$attrs"
      @register="registerDrawer"
      showFooter
      title="添加商品"
      width="620px"
      cancelText="关闭"
      okText="保存"
      @ok="onSave"
      :maskClosable="false"
  >
    <div class="card" style="width: 100%">
      <a-input-search
          v-model:value="state.search.goodsName"
          placeholder="输入产品名称搜索"
          enter-button="查询"
          allowClear
          @search="onSearch"
      />

      <template v-for="o in proCategoryType.filter((o) => o.value === 'P')"
                :key="o.value">
        <a-flex gap="small" wrap="wrap" class="cate-sub">
          <div
              :class="['use', 'cell', state.P.cateCode === null ? 'active' : 'tacit']"
              @click="state[o.value].cateCode = null"
          >全部
          </div>
          <div
              v-for="z in getCateSubList(o.value)"
              :key="z.cateCode"
              :class="[
                      'use',
                      'cell',
                      state[o.value].cateCode === z.cateCode ? 'active' : 'tacit',
                    ]"
              @click="state[o.value].cateCode = z.cateCode"
          >
            {{ z.cateSubName }}
          </div>

          <div class="btn" v-if="getCateSubAll(o.value).length > state.foldMinCount">
            <a-button
                v-if="state[o.value].hasFold"
                type="link"
                size="small"
                :icon="h(CaretDownOutlined)"
                @click="state[o.value].hasFold = false"
            >展开
            </a-button>
            <a-button
                v-else
                type="link"
                size="small"
                :icon="h(CaretUpOutlined)"
                @click="state[o.value].hasFold = true"
            >收起
            </a-button>
          </div>
        </a-flex>

        <div class="p-list">
          <template v-if="state[o.value].pager.list?.length > 0">
            <div
                :class="[
                        'use p-card',
                        state[o.value].selectedSn.has(item.goodsSn) && 'active tri-active',
                      ]"
                v-for="item in state[o.value].pager.list"
                :key="item.goodsSn"
                @click="onToggle(item, o.value)"
            >
              <a-flex gap="middle">
                <a-image
                    :width="64"
                    :height="64"
                    :src="OSS_IMG_URL(item.goodsImage)"
                    :fallback="imgErrSrc"
                />

                <a-flex class="fill right" vertical :gap="2">
                  <div class="cn-medium title">{{ item.goodsName }}</div>
                  <div class="fill"></div>
                  <a-flex gap="small" justify="space-between">
                    <div class="price"
                    ><span class="d-regular value">{{ item.salePrice }}</span
                    ><span class="unit">元</span></div
                    >
                    <div class="desc" v-if="o.value === 'P'">
                      {{ item.specs }}
                    </div>
                  </a-flex>
                </a-flex>

                <div class="tri-symbol"></div>
                <div v-if="state[o.value].selectedSn.has(item.goodsSn)" class="tri-checked">
                  <CheckOutlined/>
                </div>
              </a-flex>
            </div>

            <div class="pagination">
              <a-pagination
                  :default-page-size="state.pageSize"
                  size="small"
                  v-model:current="state[o.value].pager.currentPage"
                  :total="state[o.value].pager.totalCount"
                  show-size-changer
                  @showSizeChange="onShowSizeChange"
              />
            </div>
          </template>
          <a-empty v-else/>
        </div>

      </template>
    </div>

  </BasicDrawer>
</template>

<script setup>
import {defineOptions, h, onMounted, reactive, watch} from 'vue';

import {PAGE, POST} from '@/api/http';
import {imgErrSrc, OSS_IMG_URL, proCategoryType} from '@/api/ds';
import {CaretDownOutlined, CaretUpOutlined, CheckOutlined} from '@ant-design/icons-vue';
import {useRouter} from 'vue-router';
import {useMessage} from '@/hooks/web/useMessage';
import {BasicDrawer, useDrawerInner} from "@/components/Drawer";

const router = useRouter();
const {createMessage} = useMessage();

defineOptions({name: 'CashierConsume'});
const emit = defineEmits(['complete']);

let originConsumeIds = [];
const [registerDrawer, {closeDrawer}] = useDrawerInner(async ({consumeList}) => {
  const {P: target} = state;
  originConsumeIds =  new Set(consumeList.map((o) => o.goodsSn)),
  Object.assign(target, {
    selectedSn: new Set(consumeList.map((o) => o.goodsSn)),
    selected: consumeList,
    hasFold: true,
    cateCode: null,
  });

});


const state = reactive({
  search: {
    selectStatus: 0,
    cateType: 'P',
    goodsName: null,
  },

  foldMinCount: 6,
  pageSize: 10,

  P: {
    registerTable: null,
    table: null,
    selectedSn: new Set(),
    selected: [],
    hasFold: true,
    cateCode: null,
    version: null,
    pager: {
      currentPage: 0,
    },
  },

  categoryList: [],
});

onMounted(() => {
  onSearch();
});

function getCateWatch(cateType) {
  const target = state[cateType];
  return `${target.cateCode || ''}-${target.pager.currentPage || 0}-${target.version || ''}`;
}

watch(
    () => getCateWatch('P'),
    () => doPager('P'),
);

function getCateSubAll(cateType) {
  return state.categoryList.filter((z) => z.cateType === cateType);
}

function getCateSubList(cateType) {
  const list = getCateSubAll(cateType);
  return state[cateType].hasFold ? list.slice(0, state.foldMinCount) : list;
}

function onSearch() {
  doCategoryList();
}

function doCategoryList() {
  const {cateType, P} = state;

  POST('/product/libCategoryStoreListAll', {status: 1, cateType}).then((list) => {
    state.categoryList = list || [];

    [P].forEach((target) => {
      target.cateCode = null;
      target.pager.currentPage = 1;
      target.version = Math.random();
    });
  });
}

function doPager(cateType) {
  const {goodsName} = state.search;
  const {[cateType]: target, pageSize} = state,
      {cateCode, pager} = target,
      {currentPage} = pager;

  const url = '/product/productStoreList';
  PAGE(url)({goodsName, thirdCateCode:cateCode, currentPage, pageSize}).then((result) => {
    target.pager = result ?? {};
  });
}

function onShowSizeChange(current, size) {
    state.pageSize = size
    doPager(state.search.cateType)
  }

function onToggle(record, cateType) {
  const {selectedSn, selected} = state[cateType];
  const {goodsSn} = record;

  if (selectedSn.has(goodsSn)) {
    onDelete(record, cateType);
  } else {
    selectedSn.add(goodsSn);
    selected.push({...record});
  }
}

function onDelete({goodsSn}, cateType) {
  const {selectedSn, selected} = state[cateType];
  const index = selected.findIndex((o) => o.goodsSn === goodsSn);

  if (index > -1) {
    selected.splice(index, 1);
  }

  selectedSn.delete(goodsSn);
}

async function onSave() {
  const {P} = state;
  const [productList] = [P.selected];
  const obj = {
    deleteIds: [],
    newData: [],
  }
  // 找到被取消的配料
  obj.deleteIds = Array.from(originConsumeIds).filter(sn => !productList.find(item => item.goodsSn === sn));
  // 找到新加的配料
  productList.forEach(el => {
    if(!originConsumeIds.has(el.goodsSn)){
      obj.newData.push(el)
    }
  });
  emit('complete', obj);
  closeDrawer();
}
</script>
<style lang="less" scoped>
.card {
  height: 100%;
  padding: 16px;

  .c-title {
    padding: 32px 0 6px 8px;
    color: #091f3d;
    font-size: 15px;
    font-weight: 600;
  }

  .c-title:first-child {
    padding-top: 8px;
  }
}

.cate-sub {
  position: relative;
  cursor: pointer;

  padding-top: 12px;

  .cell {
    padding: 3px 12px;
    border-radius: 24px;
    font-size: 14px;
    font-weight: 400;
  }

  .tacit {
    border: 1px solid #e0e5ec;
    color: #091f3d;
  }

  .active {
    border: 1px solid @primary-color;
    background-color: @primary-color;
    color: #fff;
  }

  .btn {
    position: absolute;
    z-index: 2;
    right: 0;
    bottom: 0;
  }
}

.p-list {
  margin: 24px 0 0;

  .p-card {
    position: relative;
    margin: 12px 0;
    overflow: clip;
    border: 1px solid #e0e5ec;
    border-radius: 4px;

    .right {
      padding: 8px 32px 8px 0;

      .title {
        color: #091f3d;
        font-size: 14px;
      }

      .price {
        color: @primary-color;

        .value {
          font-size: 14px;
          letter-spacing: 1px;
        }

        .unit {
          padding-left: 2px;
          font-size: 10px;
        }
      }

      .desc {
        color: #acb4bf;
        font-size: 12px;
      }
    }
  }

  .pagination {
    text-align: right;
  }

  .active {
    border: 1px solid @primary-color;
  }
}
</style>
